<!--
 Copyright 2024 Administrator
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<script setup lang="ts">
defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-names
  name: "Album",
  inheritAttrs: false,
});

import {
  addAlbum,
  deleteAlbum,
  getAlbumForm,
  listAlbums,
  updateAlbum,
} from "@/api/application/album";
import {
  AlbumForm,
  AlbumQuery,
  AlbumVO,
  Pic,
} from "@/api/application/album/type";
import { listAlbumOptions, listArtistOptions } from "@/api/application/artist";
import { addBanner } from "@/api/application/banner";
import { BannerForm } from "@/api/application/banner/type";
import { getCateAllOptions } from "@/api/application/cate";
import { listSongOptions } from "@/api/application/song";
import { Category } from "@/api/cartogery/type";
import { uploadPic } from "@/api/minio";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { BannerType } from "@/enums";

import { useAudioStore } from "@/store/modules/audio";
import { Delete, InfoFilled, Plus, ZoomIn } from "@element-plus/icons-vue";
import {
  FormRules,
  UploadFile,
  UploadFiles,
  UploadInstance,
  UploadProps,
  UploadRawFile,
} from "element-plus";
import { OptionType } from "element-plus/es/components/select-v2/src/select.types";
import { storeToRefs } from "pinia";
import { onMounted, reactive, ref } from "vue";
const store = useAudioStore();
const { currentTime, currentTimeStr, lrcData, lrcText } = storeToRefs(store);

const queryFormRef = ref(ElForm);
const albumFormRef = ref(ElForm);
const albumBannerFormRef = ref(ElForm);
const queryParams = reactive<AlbumQuery>({
  pageNum: 1,
  pageSize: 10,
});
const loading = ref(false);
const filterLoading = ref(false);
const dialog = reactive({
  title: "",
  visible: false,
});
const bannerDialog = reactive({
  title: "",
  visible: false,
});

const uploadDialog = reactive({
  title: "",
  visible: false,
  active: 1,
});

const upload = ref<UploadInstance>();
const albumList = ref<AlbumVO[]>([]);
const artistOptions = ref<OptionType[]>([]);
const songOptions = ref<OptionType[]>([]);
const albumOptions = ref<OptionType[]>([]);
const cateOptions = ref<OptionType[]>([]);

const formData = reactive<AlbumForm>({
  title: "",
  genre: "",
  artistIds: [],
  downTime: new Date(),
  pushTime: new Date(),
  lang: "",
  pic: { id: "", url: "", name: "", status: "ready", uid: 0 },
  releaseDate: new Date(),
  isActive: true,
  artistList: [],
  albumAssetCode: "",
  artist: [],
  cpId: 0,
  introduce: "",
  upc: "",
  type: 0,
  pay_model: 0,
  trackList: [],
  available: false,
  availableErrMsg: "",
  isFavorite: 0,
  favoriteCount: 0,
  isPaid: 0,
  _score: 0,
  songIds: [],
});

const bannerFormData = reactive<BannerForm>({
  showEndDate: new Date(),
  showStartDate: new Date(),
  jumpLinkOutput: undefined,
  jumpType: BannerType.Album,
  sort: 0,
  showDate: "",
});

const tmpPic = ref<Pic>({ id: "", url: "", name: "", status: "ready", uid: 0 });
const removeIds = ref([]); // 删除专辑ID集合 用于批量删除

const total = ref(0); // 数据总数
// 选择表格的行专辑ID
const selectedRowAlbumId = ref<number | undefined>();

const shortcuts = computed(() => {
  const start = new Date(formData.pushTime);

  return [
    {
      text: "一周",
      value: () => {
        const end = new Date();
        console.log(formData.pushTime);

        end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: "一个月",
      value: () => {
        const end = new Date();

        end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: "三个月",
      value: () => {
        const end = new Date();
        end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ];
});

const validatePic = (rule: any, value: any, callback: any) => {
  console.log(rule, value);
  debugger;
  if (!tmpPic) {
    callback(new Error("请上传图片"));
  } else {
    if (!tmpPic.value.id) {
      uploadPic(tmpPic.value.raw!)
        .then(({ id, url }) => {
          tmpPic.value.id = id;
          tmpPic.value.url = url;
          formData.pic = tmpPic.value!;
          callback();
        })
        .catch((err) => {
          callback(new Error(err));
        });
      // try {
      //   const { fileId, url } = await uploadPic(tmpPic.value.raw!)
      //   tmpPic.value.fileId = fileId
      //   tmpPic.value.url = url
      //   formData.pic = tmpPic.value!
      //   callback()

      // } catch (error) {
      //   callback(new Error('图片上传失败'))
      // }
    } else {
      callback();
    }
  }

  // try {
  //   await uploadPic(formData!.pic!.raw!)
  //   callback()
  // } catch (error) {

  // }
};

const rules = reactive<FormRules<any>>({
  pic: [{ required: true, validator: validatePic, trigger: "submit" }],
  title: [{ required: true, message: "请选择专辑", trigger: "blur" }],
});

/**
 * 查询
 */
async function handleQuery() {
  // 重置父组件
  loading.value = true;
  try {
    const data = await listAlbums(queryParams);
    // albumList.value = data;
    albumList.value = data.list;
    total.value = data.total;
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父专辑ID
 * @param albumId 专辑ID
 */
async function openDialog(parentId?: number, albumId?: number) {
  cateOptions.value = await getCateAllOptions(2);
  // cateOptions.value = data

  dialog.visible = true;
  if (albumId) {
    dialog.title = "编辑专辑";
    const data = await getAlbumForm(albumId);
    Object.assign(formData, data);

    formData.genre = (data.genre as Category[])?.map((g) => g.id)?.at(0) ?? "";
    formData.artistIds = data?.artistList?.map((artist) => artist.id);
    artistOptions.value =
      data?.artistList?.map<any>((artist) => ({
        label: artist.name,
        value: artist.id,
      })) ?? [];
    //歌曲下拉选项
    songOptions.value =
      data?.trackList?.map((song) => ({
        label: song.title,
        value: song.id,
      })) ?? [];
    formData.songIds = data?.trackList?.map((song) => song.id) ?? [];
    // tmpPic.value = Object.assign(tmpPic,formData.pic)
    tmpPic.value = formData!.pic!;
    // tmpPic.value.id = formData.pic.id
    console.log(formData, data);
  } else {
    dialog.title = "新增专辑";
  }
}

async function openSetBannerDialog(albumId: number) {
  const data = await getAlbumForm(albumId);
  Object.assign(formData, data);

  bannerFormData.jumpLinkOutput = albumId;
  bannerDialog.visible = true;
  bannerDialog.title = "添加轮播图";
}

/** 专辑保存提交 */
function submitForm() {
  albumFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        if (formData.id) {
          await updateAlbum(formData.id, formData);
        } else {
          await addAlbum(formData);
        }

        ElMessage.success(`${formData.id ? "修改" : "新增"}成功`);

        closeDialog();
        handleQuery();
      } catch (error) {
        throw error;
      } finally {
      }
    }
  });
}

/** 专辑保存提交 */
function submitBannerForm() {
  albumBannerFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        console.log(bannerFormData);
        let showDate = bannerFormData.showDate as any;
        bannerFormData.showStartDate = showDate.at(0) ?? new Date();
        bannerFormData.showEndDate = showDate.at(1) ?? new Date();
        await addBanner(bannerFormData);

        ElMessage.success(`添加banner成功`);
        closeBannerDialog();
      } catch (error) {
        throw error;
      } finally {
      }
    }
  });
}

/** 删除专辑 */
function handleDelete(id?: number) {
  const ids = id ?? removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteAlbum(ids);
      ElMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => ElMessage.info("已取消删除"));
}
/**
 * 筛选歌曲名称
 * @param query
 */
const filterTrack = async (query: string) => {
  if (query !== "") {
    filterLoading.value = true;

    songOptions.value = await listSongOptions({
      songName: query,
      artistIds: formData.artistIds,
      pageNum: 1,
      pageSize: 10,
    });

    filterLoading.value = false;
  } else {
    songOptions.value = [];
  }
};
/**
 * 筛选歌手名称
 * @param query
 */
const filterArtist = async (query: string) => {
  if (query !== "") {
    filterLoading.value = true;
    artistOptions.value = await listArtistOptions({
      keywords: query,
      pageNum: 1,
      pageSize: 10,
    });
    filterLoading.value = false;
  } else {
    artistOptions.value = [];
  }
};

/**
 * 筛选专辑名称
 * @param query
 */
const filterAlbum = async (query: string) => {
  if (query !== "") {
    filterLoading.value = true;
    albumOptions.value = await listAlbumOptions({
      alubmName: query,
      pageNum: 1,
      pageSize: 10,
    });
    filterLoading.value = false;
  } else {
    albumOptions.value = [];
  }
};

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}
/** 关闭弹窗 */
function closeBannerDialog() {
  bannerDialog.visible = false;
  resetBannerForm();
}

/** 重置表单 */
function resetForm() {
  albumFormRef.value.resetFields();
  albumFormRef.value.clearValidate();
  formData.pic = tmpPic.value = { url: "", name: "", status: "ready", uid: 0 };

  formData.id = undefined;
}
/** 重置表单 */
function resetBannerForm() {
  albumBannerFormRef.value.resetFields();
  albumBannerFormRef.value.clearValidate();
}

const beforeImageUpload: UploadProps["beforeUpload"] = async (
  rawFile: UploadRawFile
) => {
  // if (rawFile.type !== "image/jpeg") {
  //   ElMessage.error("Avatar picture must be JPG format!");
  //   return false;
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error("Avatar picture size can not exceed 2MB!");
  //   return false;
  // }

  // const o = Object.assign({}, { ...rawFile });
  // const form: UploadFileDto = {
  //   name: "",
  //   uid: 0,
  //   status: "ready",
  //   size: 0,
  //   lastModified: 0,
  //   type: "",
  //   webkitRelativePath: "",
  //   pic: undefined,
  // };
  // form.uid = rawFile.uid;
  // form.lastModified = rawFile.lastModified;
  // form.size = rawFile.size;
  // form.type = rawFile.type;
  // form.name = rawFile.name;

  // const url = await getPresignedUrl(form);

  // uploadUrl.value = url;
  return true;
};

/**
 * 选择头像
 * @param uploadFile
 */
const avatarFileChange: UploadProps["onChange"] = async (
  uploadFile: UploadFile
) => {
  // uploadFile.url = URL.createObjectURL(uploadFile.raw!);

  tmpPic.value = {
    ...uploadFile,
    id: "",
    url: URL.createObjectURL(uploadFile.raw!),
  };
  console.log(formData.pic, tmpPic.value);
};

//删除头像
function deletePic() {
  tmpPic.value = { url: "", name: "", status: "ready", uid: 0 };
}

const handleAvatarSuccess: UploadProps["onSuccess"] = async (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {};

const confirmDelPic = async () => {
  console.log("删除");
  await deletePic();
};
const cancelDelPic = () => {};

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="专辑名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><template #icon><i-ep-search /></template>搜索</el-button
          >
          <el-button @click="resetQuery">
            <template #icon><i-ep-refresh /></template>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['sys:album:create']"
          type="success"
          @click="openDialog(0)"
        >
          <template #icon><i-ep-plus /></template>
          新增</el-button
        >
        <el-button
          v-hasPerm="['sys:album:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        :data="albumList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="id" align="left" width="50" prop="id" />
        <el-table-column label="歌手" min-width="150">
          <template #default="scope">
            {{
              scope.row.artistList.map((artist: any) => artist.name).join(",")
            }}
          </template>
        </el-table-column>
        <el-table-column label="专辑名称" min-width="150">
          <template #default="scope">
            <svg-icon :icon-class="scope.row.icon" />
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column label="标签" min-width="150">
          <template #default="scope">
            <el-tag type="info">
              {{ scope.row.genre?.at(0)?.categoryName ?? "" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="语言" align="left" width="150" prop="lang" />

        <el-table-column label="状态" align="center" width="200">
          <template #default="scope">
            <el-tag v-if="scope.row.isActive" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="介绍"
          align="center"
          width="300"
          prop="introduce"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          align="left"
          width="200"
          prop="createTime"
        />
        <el-table-column
          label="发行时间"
          align="left"
          width="200"
          prop="releaseDate"
        />
        <el-table-column
          label="上架时间"
          align="left"
          width="200"
          prop="pushTime"
        />
        <el-table-column
          label="下架时间"
          align="left"
          width="200"
          prop="downTime"
        />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:banner:create']"
              type="primary"
              link
              size="small"
              @click.stop="openSetBannerDialog(scope.row.id)"
            >
              <i-ep-plus />置为Banner
            </el-button>

            <el-button
              v-hasPerm="['sys:album:update']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(undefined, scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:album:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery"
        />
      </template>
    </el-card>

    <!-- 添加专辑 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      destroy-on-close
      append-to-body
      width="800px"
      @close="closeDialog"
      :draggable="true"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="albumFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="关联歌手" prop="artistIds">
          <el-select-v2
            v-model="formData.artistIds"
            style="width: 240px"
            multiple
            filterable
            remote
            :remote-method="filterArtist"
            clearable
            :options="artistOptions"
            :loading="filterLoading"
            placeholder="选择歌手"
          />
        </el-form-item>
        <el-form-item label="关联歌曲" prop="trackIds">
          <el-select-v2
            v-model="formData.songIds"
            style="width: 240px"
            multiple
            filterable
            remote
            :remote-method="filterTrack"
            clearable
            :options="songOptions"
            :loading="filterLoading"
            placeholder="选择歌曲"
          />
        </el-form-item>
        <el-form-item required label="专辑名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入专辑名称" />
        </el-form-item>

        <el-form-item label="封面" prop="pic">
          <div v-show="tmpPic && tmpPic.url" class="avatar-delete-wrapper">
            <img
              crossOrigin="anonymous"
              :src="tmpPic?.url ?? ''"
              class="avatar"
            />
            <span class="avatar-cover-wrapper">
              <el-icon class="avatar-icon avatar-zoomin-icon">
                <ZoomIn />
              </el-icon>
              <el-popconfirm
                placement="right"
                confirm-button-text="是"
                cancel-button-text="否"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="你确定要删除头像"
                @confirm="confirmDelPic"
                @cancel="cancelDelPic"
              >
                <template #reference>
                  <el-icon class="avatar-icon avatar-delete-icon">
                    <Delete />
                  </el-icon>
                </template>
              </el-popconfirm>
            </span>
          </div>
          <el-upload
            ref="uploadAvatarRef"
            v-show="!(tmpPic && tmpPic.url)"
            class="avatar-uploader"
            v-model="formData.pic"
            method="put"
            accept="image/bmp,image/gif,image/vnd.microsoft.icon,image/jpeg,image/webp"
            :show-file-list="false"
            :auto-upload="false"
            :on-success="handleAvatarSuccess"
            :on-change="avatarFileChange"
            :before-upload="beforeImageUpload"
          >
            <el-icon class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <!-- <el-form-item label="封面" prop="pic">
          <el-upload class="upload-demo" v-model="formData.pic">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item> -->

        <el-form-item label="标签" prop="genre">
          <el-select-v2
            v-model="formData.genre"
            filterable
            :options="cateOptions"
            placeholder="选择标签"
            style="width: 240px"
            :multiple="false"
          />
        </el-form-item>
        <el-form-item label="语言" prop="lang">
          <dictionary v-model="formData.lang" type-code="lang" />
        </el-form-item>
        <el-form-item label="发行日期" prop="pushTime">
          <el-date-picker
            v-model="formData.pushTime"
            type="date"
            placeholder="选择发行日期"
          />
        </el-form-item>
        <el-form-item label="上架时间" prop="pushTime">
          <el-date-picker
            v-model="formData.pushTime"
            type="datetime"
            placeholder="选择上架时间"
          />
        </el-form-item>
        <el-form-item label="下架时间" prop="downTime">
          <el-date-picker
            v-model="formData.downTime"
            type="datetime"
            placeholder="选择下架时间"
          />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="formData.isActive" />
        </el-form-item>
        <el-form-item label="介绍" prop="introduce">
          <el-input
            type="textarea"
            v-model="formData.introduce"
            placeholder="请输入歌手介绍"
            rows="6"
            autosize
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加轮播图 -->
    <el-dialog
      v-model="bannerDialog.visible"
      :title="bannerDialog.title"
      destroy-on-close
      append-to-body
      width="800px"
      @close="closeBannerDialog"
      :draggable="true"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="albumBannerFormRef"
        :model="bannerFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="发行日期" prop="pushTime">
          <el-date-picker
            v-model="bannerFormData.showDate"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="bannerFormData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBannerForm">确 定</el-button>
          <el-button @click="closeBannerDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.avatar {
  display: block;
  width: 178px;
  height: 178px;
  object-fit: scale-down;
}

.avatar-cover-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  // cursor: default;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  // pointer-events: none;
  width: 100%;
  height: 100%;
  font-size: 20px;
  color: #fff;
  cursor: pointer;
  background-color: var(--el-overlay-color-lighter);
  opacity: 0;
  transition: opacity var(--el-transition-duration);

  .avatar-icon {
    font-size: 20px;
  }

  .avatar-zoomin-icon {
    margin-right: 15px;
  }
}

.avatar-delete-wrapper {
  position: relative;
  border: 1px dashed gray;

  &:hover {
    .avatar-cover-wrapper {
      opacity: 1;
    }
  }
}
</style>

<style lang="scss">
.play-progress {
  margin-bottom: 15px;
}

.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
